package com.example.demo.common.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSAUtils {
    public static Map<String, String> getKeyPair() {
        Map<String, String> keyMap = new HashMap<>();
        try {
            //KeyPairGenerator可以用于生成公钥和私钥，这里设置了使用RSA算法来生成公钥私钥
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            //密钥对初始化
            keyPairGenerator.initialize(1024, new SecureRandom());
            //生成密钥对，保存在KeyPair中
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            //私钥
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            //公钥
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            //得到公钥字符串
            String PublicStringKey = new String(Base64.encodeBase64(publicKey.getEncoded()));
            //得到私钥字符串
            String PrivateStringKey = new String(Base64.encodeBase64(privateKey.getEncoded()));
            //保存到MAP中返回
            keyMap.put("publicKey", PublicStringKey);
            keyMap.put("privateKey", PrivateStringKey);
        } catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
        return keyMap;
    }

    //私钥解密
    public static String decrypt(String endPassword,String privateKey){
        String password;
        try{
            byte[] inputType = Base64.decodeBase64(endPassword.getBytes(StandardCharsets.UTF_8));
            byte[] decoded = Base64.decodeBase64(privateKey);
            RSAPrivateKey privateKey1 = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE,privateKey1);
            password = new String(cipher.doFinal(inputType));
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return password;
    }
}
